import { AbpWindowService } from '@abp/ng.core';
import { Component, inject } from '@angular/core';
import { PersonDto, PersonListInput, PersonService } from '@proxy/people';
import { NzTableQueryParams } from 'ng-zorro-antd/table';
import { NzUploadXHRArgs } from 'ng-zorro-antd/upload';

const ExcelContentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

@Component({
  selector: 'app-person',
  templateUrl: './person.component.html',
  styleUrl: './person.component.scss'
})
export class PersonComponent {
  total = 0;
  items: PersonDto[] = [];

  pageSize = 10;
  pageIndex = 1;
  filter = '';
  loading = false;

  private get request(): PersonListInput {
    return {
      filter: this.filter,
      maxResultCount: this.pageSize,
      skipCount: this.pageSize * (this.pageIndex - 1)
    };
  }

  private _personService = inject(PersonService);
  private _windowService = inject(AbpWindowService);

  loadData() {
    console.log('loadData');
    this.loading = true;

    this._personService.getList(this.request).subscribe(res => {
      this.items = res.items.map(item => ({ key: item.id, ...item }));
      this.total = res.totalCount;
      this.loading = false;
    });
  }

  pageHandle(query: NzTableQueryParams) {
    this.pageIndex = query.pageIndex;
    this.pageSize = query.pageSize;
    this.loadData();
  }

  refresh() {
    this.pageIndex = 1;
    this.loadData();
  }

  // #region 上传数据
  uploading = false;
  importData = (args: NzUploadXHRArgs) => {
    this.uploading = true;
    const myFormData = new FormData();
    myFormData.append('file', args.postFile as Blob);
    return this._personService.importExcel(myFormData).subscribe(() => {
      this.loadData();
      this.uploading = false;
    });
  };
  // #endregion

  // #region 添加或修改
  createHandle() {
    this.currentItem = null;
    this.isShowEditor = true;
  }

  editHandle(item: PersonDto) {
    this.currentItem = item;
    this.isShowEditor = true;
  }

  isShowEditor = false;
  currentItem: PersonDto | null = null;
  // #endregion

  //#region 导出
  downloadTemplate() {
    this.isDownloadTemplate = true;
    this._personService.exportTemplate().subscribe(res => {
      const blob = new Blob([res], { type: ExcelContentType });
      this._windowService.downloadBlob(blob, '人员模板.xlsx');
      this.isDownloadTemplate = false;
    });
  }

  isDownloadTemplate = false;

  //#endregion

  // #region 导出数据
  downloadData() {
    this.isDownloadData = true;
    this._personService.exportAll().subscribe(res => {
      const blob = new Blob([res], { type: ExcelContentType });
      this._windowService.downloadBlob(blob, '人员信息.xlsx');
      this.isDownloadData = false;
    });
  }

  isDownloadData = false;

  // #endregion

  // #region 清空
  isClear = false;

  clearHandle() {
    this.isClear = true;
    this._personService.clearAll().subscribe(_ => {
      this.refresh();
      this.isClear = false;
    });
  }

  // #endregion
}
